package com.ciquan.server.util;



import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.File;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.List;

/**
 * Http&Https连接Util类
 * 
 * @author fei.bian
 * 
 */
public class URLConnUtils {

    private static Logger logger = Logger.getLogger(URLConnUtils.class.getName());

	public static final int DEFAULT_CONN_TIMEOUT = 60000;
	public static final int DEFAULT_SO_TIMEOUT = 60000;

    private static final ContentType TEXT_PLAIN = ContentType.create("text/plain", Charset.forName("UTF-8"));

    public static String doGet(String url, List<NameValuePair> params) {
        return doGet(url, params, DEFAULT_CONN_TIMEOUT, DEFAULT_SO_TIMEOUT, "UTF-8");
    }

    public static String doPost(String url, List<NameValuePair> params) {
        return doPost(url, params, DEFAULT_CONN_TIMEOUT, DEFAULT_SO_TIMEOUT, "UTF-8", "UTF-8");
    }

    public static String doMultiPost(String url, List<Part> parts) {
        return doPost(url, parts, 3 * DEFAULT_CONN_TIMEOUT, 3 * DEFAULT_SO_TIMEOUT, "UTF-8");
    }

	/**
	 * http get 有参数，可设置是否打印Log，日志过滤敏感参数
	 * @param url
	 * @param params
	 * @param connTimeOut
	 * @param soTimeOut
	 * @return
	 */
	private static String doGet(String url, List<NameValuePair> params,
			int connTimeOut, int soTimeOut, String contentEncode) {

		HttpGet httpget = null;
		String respContent = null;
		HttpEntity entity = null;

		DefaultHttpClient httpclient = new DefaultHttpClient();

		HttpParams httpparams = httpclient.getParams();
		HttpConnectionParams.setConnectionTimeout(httpparams, connTimeOut);
		HttpConnectionParams.setSoTimeout(httpparams, soTimeOut);

		try {
			httpget = new HttpGet(url);
			if (params != null && params.size() > 0) {
				httpget.setURI(new URI(httpget.getURI().toString()
						+ "?"
						+ EntityUtils.toString(new UrlEncodedFormEntity(params,
								HTTP.UTF_8))));
			}
            logger.info("url=" + httpget.getURI().toString());
			HttpResponse httpresp = httpclient.execute(httpget);
			entity = httpresp.getEntity();
			respContent = EntityUtils.toString(entity,contentEncode);
		} catch (Exception e) {
            logger.error("exception", e);
        } finally {
			if (httpget != null) {
				httpget.abort();
			}
			if (httpclient != null) {
				httpclient.getConnectionManager().shutdown();
			}
		}
		return respContent;
	}
	
	/**
	 * http post 有参数，可设置是否打印Log，日志过滤敏感参数
	 * @param url
	 * @param params
	 * @param connTimeOut
	 * @param soTimeOut
	 * @return
	 */
	public static String doPost(String url, List<NameValuePair> params,
			int connTimeOut, int soTimeOut, String reqCharset,String resCharset) {

		HttpPost httppost = null;
		String respContent = null;
		HttpEntity entity = null;

		DefaultHttpClient httpclient = new DefaultHttpClient();

		HttpParams httpparams = httpclient.getParams();
		HttpConnectionParams.setConnectionTimeout(httpparams, connTimeOut);
		HttpConnectionParams.setSoTimeout(httpparams, soTimeOut);

		try {
			httppost = new HttpPost(url);

			// 设置参数
			if (params != null && params.size() > 0) {
				httppost.setEntity(new UrlEncodedFormEntity(params, reqCharset));
			}

			HttpResponse httpresp = httpclient.execute(httppost);
			// 获取返回数据
			entity = httpresp.getEntity();
			respContent = EntityUtils.toString(entity,resCharset);
		} catch (Exception e) {
            logger.error("exception", e);
		} finally {
			// 关闭资源
			if (httppost != null) {
				httppost.abort();
			}
			if (httpclient != null) {
				httpclient.getConnectionManager().shutdown();
			}
		}
		return respContent;
	}


    public static String doPost(String url, List<Part> parts,
                                int connTimeOut, int soTimeOut, String resCharset) {

        HttpPost httppost = null;
        String respContent = null;
        HttpEntity entity = null;

        DefaultHttpClient httpclient = new DefaultHttpClient();

        HttpParams httpparams = httpclient.getParams();
        httpparams.setParameter("charset", "UTF-8");
        HttpConnectionParams.setConnectionTimeout(httpparams, connTimeOut);
        HttpConnectionParams.setSoTimeout(httpparams, soTimeOut);

        try {
            httppost = new HttpPost(url);

            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
            for(Part part : parts) {
                if(part.value instanceof String) {
                    multipartEntityBuilder.addTextBody(part.name, (String) part.value, TEXT_PLAIN);
                }

                else {
                    ByteArrayBody byteArrayBody = new ByteArrayBody((byte[]) part.value, "upload.jpg");
                    multipartEntityBuilder.addPart(part.name, byteArrayBody);
                }
            }

            httppost.setEntity(multipartEntityBuilder.build());

            HttpResponse httpresp = httpclient.execute(httppost);
            // 获取返回数据
            entity = httpresp.getEntity();
            respContent = EntityUtils.toString(entity,resCharset);
        } catch (Exception e) {
            logger.error("exception", e);
        } finally {
            // 关闭资源
            if (httppost != null) {
                httppost.abort();
            }
            if (httpclient != null) {
                httpclient.getConnectionManager().shutdown();
            }
        }
        return respContent;
    }

    public static void addParam(List<NameValuePair> params, String name,
                                String value) {
        params.add(new BasicNameValuePair(name, value));
    }

    public static void addMultiParam(List<Part> params, String name,
                                Object value) {

        if(StringUtils.isBlank(name) || value == null) {
            return;
        }

        params.add(new Part(name, value));
    }

    public static class Part {
        String name;
        Object value;

        public Part(String name, Object value) {
            this.name = name;
            this.value = value;
        }
    }


}
